package com.blog.controller;

import com.blog.pojo.Article;
import com.blog.pojo.Tag;
import com.blog.service.ArticleService;
import com.blog.service.TagService;
import com.blog.service.impl.ArticleServiceImpl;
import com.blog.service.impl.TagServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/NewArticleServlet.do")
public class NewArticleServlet extends HttpServlet {


    ArticleService articleService=new ArticleServiceImpl();

    TagService tagService=new TagServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //处理请求乱码
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");

        try {
            String title = req.getParameter("title");
            String time = req.getParameter("time");
            String author = req.getParameter("author");
            String sort = req.getParameter("sort");
            String content = req.getParameter("content");
            String tags = req.getParameter("tags");
            //封装对象  Article(Integer id, String title, String author, String sort, String time, Integer star, Integer comment, Integer visit, String content)
            Article article=new Article(null,title,author,sort,time,0,0,0,content);
            //新增文章到数据库
            int count=articleService.add(article);
            if(count>0){
                Article lastedArticle = articleService.getLastedArticle();
                String[] arraysTags = tags.split(" ");
                for (String tagName : arraysTags) {
                    if(!"".equals(tagName)){
                        Tag tag=new Tag(lastedArticle.getId(),tagName);
                        tagService.add(tag);
                    }
                }
            }
            resp.getWriter().write("<script>alert('文章发布成功！');location.href='/Blog/IndexServlet.do';</script>");
        } catch (Exception e) {
            e.printStackTrace();
            resp.getWriter().write("<script>alert('文章发布异常！');location.href='/Blog/GoAddArticelServlet.do';</script>");
        }

    }
}
